'use strict';
const fiip = require('fiip');
const Link = fiip.Link;

const startServer = (ip, port) => {
  const dgram = require('dgram');
  const link = new Link.Client();
  link.type = Link.type.udp;
  link.status = Link.status.server;
  link.address = ip;
  link.port = port;
  link.fd = dgram.createSocket('udp4');
  link.fd.bind(link.port);
  link.send = (data, dataLen, link) => {
    if (this.type == Link.type.udp) this.fd.send(data.slice(0, dataLen), this.port, this.address);
    else link.fd.send(data.slice(0, dataLen), link.port, link.address);
  };
  link.recv = fiip.recv.bind(fiip);

  link.fd.on('message', (data, rinfo) => {
    let rlink = new Link.Client();
    rlink.type = Link.type.udp;
    rlink.status = Link.status.temp;
    rlink.address = rinfo.address;
    rlink.port = rinfo.port;
    rlink.fd = link.fd;
    rlink.send = link.send.bind(rlink);
    rlink.recv = link.recv;
    rlink.recv(data, data.length, rlink);
  });
  link.fd.on('error', (error) => {
    console.error('fiip-link-udp/server: error:', error);
  });
  link.fd.on('close', () => {
    console.error('fiip-link-udp/server: close');
  });

  return link;
};

module.exports = startServer;
